package com.hcc.gateway.netty.support;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.SneakyThrows;

import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * TemplateUtils
 *
 * @author shengjun.hu
 * @date 2021/6/7
 */
public class TemplateUtils {

    private TemplateUtils() {}

    /**
     * 转换freemaker模板
     * @param modelName 模型名称，根据此名称映射到模板中
     * @param templateContent 模板内容
     * @param data 转换模板需要的数据
     * @param <T>
     * @return
     * @throws Exception
     */
    @SneakyThrows
    public static <T> String convertFreeMakerTemplate(String modelName, String templateContent, T data) {
        Configuration ftlConfig = new Configuration(Configuration.VERSION_2_3_31);

        Template template = new Template(modelName, templateContent, ftlConfig);
        Map<String, Object> map = new HashMap<>();
        map.put(modelName, data);

        StringWriter stringWriter = new StringWriter();
        template.process(map, stringWriter);

        return stringWriter.toString();
    }

    @SneakyThrows
    public static <T> String convertFreeMakerTemplate(String templateContent, Object obj) {
        Configuration ftlConfig = new Configuration(Configuration.VERSION_2_3_31);

        Template template = new Template("", templateContent, ftlConfig);

        StringWriter stringWriter = new StringWriter();
        template.process(obj, stringWriter);

        return stringWriter.toString();
    }

}
